package com.atguigu.yygh.user.service.impl;


import com.atguigu.yygh.common.exception.HospitalException;
import com.atguigu.yygh.common.helper.JwtHelper;
import com.atguigu.yygh.common.result.ResultCodeEnum;
import com.atguigu.yygh.enums.AuthStatusEnum;
import com.atguigu.yygh.model.user.Patient;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.model.user.UserLoginRecord;
import com.atguigu.yygh.user.mapper.UserInfoMapper;
import com.atguigu.yygh.user.service.PatientService;
import com.atguigu.yygh.user.service.UserInfoService;
import com.atguigu.yygh.vo.user.LoginVo;
import com.atguigu.yygh.vo.user.UserAuthVo;
import com.atguigu.yygh.vo.user.UserInfoQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.print.attribute.HashPrintJobAttributeSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private PatientService patientService;
    @Override
    public Map<String, Object> loginUser(LoginVo loginVo) {
        //从登录用户实体中获取手机号和验证码
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();
        log.info("输入的验证码{}",code);
        //判断手机号验证码是否为null
        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)){
            throw new HospitalException(ResultCodeEnum.PARAM_ERROR);
        }
        //判断存在测redis中的code和登录时输入的code知否相同
        //模拟的验证码是194744
        ValueOperations opsForValue = redisTemplate.opsForValue();
        String mobleCode  = (String) opsForValue.get(phone);
        log.info("redis取到的验证码是{}",mobleCode);
        if(!code.equals(mobleCode)) {
            throw new HospitalException(ResultCodeEnum.CODE_ERROR);
        }
        //绑定手机号码
        UserInfo userInfo = null;
        if(!StringUtils.isEmpty(loginVo.getOpenid())) {
            userInfo = this.getByOpenid(loginVo.getOpenid());
            if(null != userInfo) {
                userInfo.setPhone(loginVo.getPhone());
                this.updateById(userInfo);
            } else {
                throw new HospitalException(ResultCodeEnum.DATA_ERROR);
            }
        }
//userInfo=null 说明手机直接登录
        if(null == userInfo) {

            //判断是否第一次登录，根据数据库查询手机号是否存在
            QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("phone", phone);
            userInfo = baseMapper.selectOne(wrapper);
            if (null == userInfo) {
                //第一次
                userInfo = new UserInfo();
                userInfo.setName("");
                userInfo.setPhone(phone);
                userInfo.setStatus(1);
                this.save(userInfo);
            }
        }
        //不是第一次就直接登录 校验
        if(userInfo.getStatus() == 0) {
            throw new HospitalException(ResultCodeEnum.LOGIN_DISABLED_ERROR);
        }
        //返回信息
        Map<String, Object> map = new HashMap<>();
        String name = userInfo.getName();
        if(StringUtils.isEmpty(name)) {
            name = userInfo.getNickName();
        }
        if(StringUtils.isEmpty(name)) {
            name = userInfo.getPhone();
        }
        map.put("name", name);
        //token  使用id和 name生成token
        String token = JwtHelper.createToken(userInfo.getId(), name);
        map.put("token", token);
        return map;

    }


    @Override
    public UserInfo getByOpenid(String openId) {
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("openid",openId);
        return baseMapper.selectOne(wrapper);
    }

    @Override
    public void auth(Long userId, UserAuthVo userAuthVo) {
        //根据id获取信息
        UserInfo userInfo = baseMapper.selectById(userId);

        //设置认证信息
        //认证人姓名
        userInfo.setName(userAuthVo.getName());
        //其他认证信息
        userInfo.setCertificatesType(userAuthVo.getCertificatesType());
        userInfo.setCertificatesNo(userAuthVo.getCertificatesNo());
        userInfo.setCertificatesUrl(userAuthVo.getCertificatesUrl());
        userInfo.setAuthStatus(AuthStatusEnum.AUTH_RUN.getStatus()); //认证信息  AUTH_RUN(1, "认证中"),这是认证中，平台系统做左后认证
        //进行信息更新
        baseMapper.updateById(userInfo);

    }

    @Override
    public IPage<UserInfo> selectPage(Page<UserInfo> userInfoPage, UserInfoQueryVo userInfoQueryVo) {
        String keyword = userInfoQueryVo.getKeyword();  //用户名称
        Integer status = userInfoQueryVo.getStatus();    //用户状态
        Integer authStatus = userInfoQueryVo.getAuthStatus(); //认证状态
        String createTimeBegin = userInfoQueryVo.getCreateTimeBegin(); //开始时间
        String createTimeEnd = userInfoQueryVo.getCreateTimeEnd();  //结束时间
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(keyword)) {
            wrapper.eq("name", keyword);
        }
        if (!StringUtils.isEmpty(status)) {
            wrapper.eq("status", status);}
            if (!StringUtils.isEmpty(authStatus)) {
                wrapper.eq("auth_status", authStatus);
            }
            if (!StringUtils.isEmpty(createTimeBegin)) {
                wrapper.ge("create_time", createTimeBegin);   //大于开始时间
            }
            if (!StringUtils.isEmpty(createTimeEnd)) {
                wrapper.le("create_time", createTimeEnd);    //小于结束时间
            }
            IPage<UserInfo> userInfoPage1 = baseMapper.selectPage(userInfoPage, wrapper);
            //身份编号转化为值
            userInfoPage1.getRecords().stream().forEach(item -> {
                this.packageUserInfo(item);
            });
            return userInfoPage1;


    }

    @Override
    public void lock(Long userId, Integer status) {
        if (status.intValue() ==0 || status.intValue() ==1){
            UserInfo userInfo = baseMapper.selectById(userId);
            userInfo.setStatus(status);
            baseMapper.updateById(userInfo);
        }
    }

    @Override
    public Map<String, Object> show(Long userId) {
        HashMap<String, Object> map = new HashMap<>();
        //用户信息
        UserInfo userInfo = baseMapper.selectById(userId);
        UserInfo packageUserInfo = this.packageUserInfo(userInfo);
        map.put("userInfo",packageUserInfo);
        //添加就诊人信息
        List<Patient> patientList = patientService.findAllUserId(userId);
        map.put("patientList",patientList);
        return map;

    }
    //认证审批  2为审核通过 -1为不通过
    @Override
    public void approval(Long userId, Integer authStatus) {
        if (authStatus.intValue()==2 || authStatus.intValue() ==-1){
            UserInfo userInfo = baseMapper.selectById(userId);
            userInfo.setAuthStatus(authStatus);
            baseMapper.updateById(userInfo);
        }
    }

    private UserInfo packageUserInfo (UserInfo userInfo){
           //处理认证编号
            userInfo.getParam().put("authStatusString",AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus()));
            //处理用户状态 0  1
            String statusString =userInfo.getStatus().intValue() == 0 ? "锁定" : "正常";
            userInfo.getParam().put("statusString",statusString);
            return userInfo;
        }

    }